package leetcode;

import java.util.HashSet;
import java.util.Set;

public class LeetCode141 {
    public boolean hasCycle1(ListNode head) {
        Set<ListNode> set = new HashSet<>();
        while (head != null) {
            if (set.contains(head)) {
                return true;
            }
            set.add(head);
            head = head.next;
        }
        return false;
    }
//------------------------------------------------------------------

    //快慢指针
    //在环型上会相遇 速度差2-1=1
    //链表 空间O(1) 使用快慢指针/滑动窗口
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode fast = head.next;
        //如果是环永远不结束
        while (fast != head) {
            if (fast == null || fast.next == null)
                return false;
            fast = fast.next.next;
            head = head.next;
        }
        return true;
    }
}
